<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>测试界面</title>
</head>

<body>

<div>
  <input type="text" style="width: 20%" value="ws://127.0.0.1:8080/websocket/message" id="url">
  <button id="btn_join">连接</button>
  <button id="btn_exit">断开</button>
</div>
<br/>
<textarea id="message" cols="100" rows="9"></textarea> <button id="btn_send">发送消息</button>
<br/>
<br/>
<textarea id="text_content" readonly="readonly" cols="100" rows="9"></textarea>返回内容
<br/>
<br/>
<script src="./jq.js"></script>
<script type="text/javascript">

    var ws = null;
    // 连接
    document.querySelector('#btn_join').onclick = function() {
      var url = document.querySelector("#url").value;
      ws = new WebSocket(url);
      ws.onopen = function(event) {
        document.querySelector('#text_content').innerHTML += '已经打开连接!' + '\n';
      }
      ws.onmessage = function(event) {
        document.querySelector('#text_content').innerHTML += event.data + '\n';
      }
      ws.onclose = function(event) {
        document.querySelector('#text_content').innerHTML += '已经关闭连接!' + '\n';
      }
    }
    // 发送消息
    document.querySelector('#btn_send').onclick = function() {
      var message = document.querySelector('#message').value;
      if (ws) {
        ws.send(message);
      } else {
        alert("未连接到服务器");
      }
    }
    //断开
    document.querySelector('#btn_exit').onclick = function() {
      if (ws) {
        ws.close();
        ws = null;
      }
    }

</script>
</body>
</html>
